<!-- 人事-基础设置-人才标签设置 -->
<template>
  <ContentCard>
    <template #header>
      <pageHeaderNew
        :title="title"
        :breadCrumb="breadCrumb"
        showBack
      ></pageHeaderNew>
    </template>
    <ConditionBox :margin-bottom="20">
      <template #right>
        <a-button type="primary" @click="add">新增分类</a-button>
        <a-button type="outline" status="danger" @click="remove(null)"
          >批量删除分类</a-button
        >
      </template>
    </ConditionBox>
    <TableTurn ref="tableRef" :tableData="getTableData" :args="args">
      <a-table-column
        :width="150"
        title="标签分类"
        data-index="name"
        align="center"
      ></a-table-column>
      <a-table-column title="拥有标签" align="center" data-index="remark">
        <template #cell="{ record, rowIndex }">
          <div :ref="(e, id) => setRefs(e, record.id)" class="tag-box">
            <a-tag
              @click="tagClick(tag)"
              class="tag"
              v-for="(tag, index) of sliceTag[rowIndex] > 0
                ? record.subTag.slice(0, sliceTag[rowIndex])
                : record.subTag"
              :key="tag.id"
              closable
              @close="removeSub(tag.id)"
              :color="TAG_COLOR_ENUMS[index % TAG_COLOR_ENUMS.length]"
            >
              <span> {{ tag.name }}</span>
            </a-tag>
            <a-button
              @click="showMoreTags(record.subTag)"
              v-if="sliceTag[rowIndex] > 0"
              type="text"
              >查看更多</a-button
            >
            <a-tag
              :style="{
                width: '90px',
                backgroundColor: 'var(--color-fill-2)',
                border: '1px dashed var(--color-fill-3)',
                cursor: 'pointer'
              }"
              @click="addSub(record.id)"
            >
              <template #icon>
                <icon-plus />
              </template>
              新增子标签
            </a-tag>
          </div>
        </template>
      </a-table-column>
      <a-table-column align="center" title="操作" :width="200" fixed="right">
        <template #cell="{ record }">
          <a-space :size="0">
            <a-tooltip content="编辑">
              <IconFont
                type="icon-edit"
                :size="26"
                :style="{
                  cursor: 'pointer'
                }"
                @click="goEdit(record)"
              />
            </a-tooltip>
            <a-tooltip content="删除" position="left">
              <a-popconfirm
                content="是否确认删除该条数据?"
                position="left"
                @ok="remove(record.id)"
              >
                <IconFont
                  type="icon-delete"
                  :size="26"
                  :style="{
                    cursor: 'pointer'
                  }"
                />
              </a-popconfirm>
            </a-tooltip>
          </a-space>
        </template>
      </a-table-column>
    </TableTurn>
  </ContentCard>
  <AddLabel
    style="z-index: 9999"
    v-model:visible="modalVisible"
    @labelAddEmit="labelAddEmit"
    :data="currData"
    :tagType="currTagType as 1 || 2"
  >
  </AddLabel>
</template>

<script lang="tsx" setup>
import {
  GetHumanLabel,
  DelHumanLabel,
  PostHumanLabel,
  PutHumanLabel,
  PutHumanSubLabel,
  PostHumanSubLabel,
  DelHumanSubLabel,
  CheckumanLabel,
  GetHumanSubLabel,
  GetHumanSubLabelRepeat
} from '@/apis/management/human/baseSetting/humanSetting';
import { validateRules } from '@/utils/common';
import AddLabel from './components/AddLabel/index.vue';
import { Modal, Tag, Message, Space } from '@arco-design/web-vue';
import { TAG_COLOR_ENUMS } from '@/utils/constants';

const title = '人才标签设置';

const breadCrumb: string[] = ['人事', '基础设置', '人才标签设置'];

// 表格配置
const args = reactive({
  rowSelection: {
    type: 'checkbox',
    showCheckedAll: true,
    onlyCurrent: false
  }
});
let tableRef = ref();

/* 储存选择的数据 */
const selectedList = computed(() => tableRef.value.selectedList);

let list = ref(); // 储存标签数据
let currData = ref({
  name: ''
}); // 当前点击的数据
let tags = ref([]);
let currTagType = ref(1);
// 获取数据
const getTableData = async () => {
  const { perTagTypeList } = await GetHumanLabel({});
  list.value = perTagTypeList;
  const { perTagList } = await GetHumanSubLabel({ tagTypeId: 7 });
  tags.value = perTagList;
  return Promise.resolve(list.value);
};

let tagSubRefs = ref([]);
let setRefs = (e, id) => {
  tagSubRefs.value[id] = e;
};

let sliceTag = ref([]); // 储存每个标签要截取的子标签个数
watch(
  () => tagSubRefs.value,
  (newVal) => {
    console.log('tagSubRefs.value:', tagSubRefs.value);
    let width = 0;
    for (let i in newVal) {
      if (newVal[i]) {
        // 获取表格的宽度然后减去查看更多按钮和新增子标签按钮的宽度
        width = newVal[i]?.offsetWidth - 360;

        let subWidth = 0; // 储存子标签的宽度
        const tags = newVal[i].querySelectorAll('.tag');
        for (let j = 0; j < tags.length; j++) {
          if (subWidth >= width) {
            sliceTag.value.push(j);
            break;
          }
          subWidth += tags[j]?.offsetWidth;
        }
        sliceTag.value.push(0);
      }
    }
    sliceTag.value.splice(-1, 1);
    sliceTag.value.reverse();
  },
  {
    deep: true
  }
);

let modalVisible = ref(false); // 判断新增分类弹出框

// 新增弹出框
const add = () => {
  currData.value = {
    name: ''
  };
  currTagType.value = 1;
  modalVisible.value = true;
};

// 重命名主类
const goEdit = (data: any) => {
  currData.value = data;
  currTagType.value = 1;
  modalVisible.value = true;
};

// 确认删除主标签
const remove = async (id: number | null) => {
  try {
    if (!id) {
      if (selectedList.value.length === 0) {
        Message.error('请至少选择一项！');
      } else {
        Modal.confirm({
          title: '提示',
          content: '确定要删除选中的数据吗？',
          onOk: async () => {
            try {
              await DelHumanLabel({
                ids: selectedList.value
              });
              tableRef.value.selectedList = [];
              refresh();
            } catch (error: unknown) {
              console.log(error);
            }
          }
        });
      }
    } else {
      await DelHumanLabel({
        ids: [id]
      });
      tableRef.value.selectedList = [];
      refresh();
    }
  } catch (error: unknown) {
    console.log(error);
  }
};

// 确认新增一个子类
const addSub = async (tagTypeId: number) => {
  try {
    currData.value = {
      name: '',
      tagTypeId
    };
    currTagType.value = 2;
    modalVisible.value = true;
  } catch (error: unknown) {
    console.log(error);
  }
};

let currTagId = ref(0); // 当前选中的子标签id
let currId = ref(0); // 当前选中的主标签id
const tagClick = (record: any) => {
  currTagId.value = record.id;
  currData.value = record;
  currTagType.value = 2;
  modalVisible.value = true;
};

// 删除子类
const removeSub = async (id: number) => {
  await DelHumanSubLabel({
    ids: [id]
  });
  refresh();
};

// 新增主分类自定义事件
const labelAddEmit = async (data: any) => {
  try {
    if (currTagType.value === 1) {
      // 编辑主分类名字
      if (data.id) {
        await PutHumanLabel({
          name: data.name,
          id: data.id
        });
      }
      // 新增主分类名字
      else {
        await PostHumanLabel({
          name: data.name
        });
      }
    }
    // 处理子分类名字
    else {
      if (data.id) {
        await PutHumanSubLabel({
          name: data.name,
          id: data.id
        });
      }
      // 新增子分类名字
      else {
        await PostHumanSubLabel({
          name: data.name,
          tagTypeId: data.tagTypeId
        });
      }
    }
    console.log('=======data=============================');
    console.log(data);
    console.log('====================================');
    refresh();
  } catch (error: unknown) {
    console.log(error);
  }
};

// 显示更多标签弹窗
const showMoreTags = (subs) => {
  const content = (
    <>
      {
        <Space>
          {subs.map((tag, index) => {
            return (
              <Tag
                closable
                onClose={() => removeSub(tag.id)}
                class="tag"
                color={TAG_COLOR_ENUMS[index % TAG_COLOR_ENUMS.length]}
              >
                {tag.name}
              </Tag>
            );
          })}
        </Space>
      }
    </>
  );
  Modal.open({
    title: '更多标签',
    content
  });
};

const refresh = () => {
  tableRef.value.loadData();
};
</script>

<style scoped lang="less">
.tag-box {
  // 不能换行
  white-space: nowrap;
  .tag {
    cursor: pointer;
    margin-right: 10px;
  }
}

.wrap {
  padding: 10px 20px;

  .container {
    margin-top: 20px;
    &-header {
      // display: flex;
      position: relative;
      height: 36px;
      border-radius: 4px;
      line-height: 36px;
      font-weight: 700;
      /* 自动布局 */
      padding: 7px 16px 7px 0px;
      margin-bottom: 10px;
      background: #edeffd;
    }
    &-header::before {
      position: relative;
      top: 5px;
      left: 10px;
      display: inline-block;
      height: 25px;
      width: 5px;
      margin-right: 20px;
      border-radius: 2px;
      // transform: translateY(-50%);
      content: '';
      background-color: #165dff;
    }
  }
}
</style>
